package com.syzg.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class SecurityUtil
{
  public static byte[] md5(byte[] input)
  {
    try
    {
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      return md5.digest(input);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }

  public static byte[] md5(String input) {
    try {
      return md5(input.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  public static String md5Hex(byte[] input) {
    return ByteUtil.byteToHex(md5(input));
  }

  public static String md5Hex(String input)
  {
    try {
      return md5Hex(input.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  public static String desEncryptHex(String input, String secretKey) {
    if ((secretKey.length() != secretKey.getBytes().length) || (secretKey.length() != 8)) {
      throw new IllegalArgumentException("密钥得匘个单字节字符(英文字母,数字,标点符号)组成.");
    }
    try
    {
      DESKeySpec key = new DESKeySpec(secretKey.getBytes());
      SecretKey skey = SecretKeyFactory.getInstance("DES").generateSecret(key);
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(1, skey);
      return ByteUtil.byteToHex(cipher.doFinal(input.getBytes("UTF-8")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static String desDecryptString(String inputHex, String secretKey) {
    if ((secretKey.length() != secretKey.getBytes().length) || (secretKey.length() != 8))
      throw new IllegalArgumentException("密钥得由8个单字节字符(英文字母,数字,标点符号等)组成.");
    try
    {
      DESKeySpec key = new DESKeySpec(secretKey.getBytes());
      SecretKey skey = SecretKeyFactory.getInstance("DES").generateSecret(key);
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(2, skey);
      return new String(cipher.doFinal(ByteUtil.hexToByte(inputHex)), "UTF-8");
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}